<?php


namespace app\queue\stomp;


use app\queue\BaseConsumer;
use common\model\EntityModel;
use common\model\NoteModel;
use common\model\UserModel;
use common\service\NoteService;
use common\service\OptionsService;
use Webman\Stomp\Client;

/**
 * 需求关联关系发生变更通知相关人员
 * Class SyncDesignRelationData
 * @package app\queue\redis
 */
class NoteRelationChangeNotifyConsumer extends BaseConsumer
{

    // 要消费的队列名
    public $queue = 'note_relation_change_notify';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';

    /**
     * @param $data
     * @return void
     */
    public function doConsume($data)
    {
        try {
            $changeType = $data['type'];
            $changedRelations = array_values($data['changed']);
            // 通过note_id来 分组通知
            $changedRelationsGrouped = array_group_by($changedRelations, 'note_id');
            $notifyText = '';
            switch ($changeType) {
                case 'add':
                    $notifyText = "关联了新的需求";
                    break;
                case 'deleted':
                    $notifyText = "取消关联了需求";
                    break;
                default:
                    return;
            }
            $noteList = model(NoteModel::class)->where(['id' => ['IN', implode(',', array_keys($changedRelationsGrouped))]])->select();
            $noteList = array_column($noteList, null, 'id');
            foreach ($changedRelationsGrouped as $noteId => $changedRelations) {
                $note = $noteList[$noteId] ?? null;
                if (empty($note)) {
                    continue;
                }
                $creator = model(UserModel::class)->find($note['created_by']);
                $changedRelations = array_group_by($changedRelations, 'relation_type');
                foreach ($changedRelations as $relationType => $relations) {
                    $relateTasks = NoteService::getInstance()->getDemandSpecifiedRelationTasksAndPeople($relations, false);
                    $linkToData = [];
                    $groupKeyText = [];
                    switch ($relationType) {
                        case 'episode':
                            $templateId = OptionsService::getInstance()->getDemandRemindCommonTemplateId();
                            $relateTasksGrouped = [];
                            foreach ($relateTasks as $relateTask) {
                                $k = $relateTask['initial_episode_code'];
                                $relateTasksGrouped[$k][] = $relateTask;
                                $groupKeyText[$k] = $k;
                                if (!isset($linkToData[$k])) {
                                    $linkToData[$k] = [
                                        'demand_id' => $noteId,
                                        'tenant_id' => $relateTask['tenant_id'],
                                        'project_id' => $relateTask['project_id'],
                                        'message_key' => 'episode_demand_change',
                                    ];
                                }
                            }
                            break;
                        case 'entity':
                            $templateId = OptionsService::getInstance()->getEntityTaskRemindCommonTemplateId();
                            $relateTasksGrouped = [];
                            // 处理实体id  转换成清单的实体id
                            $entityIdList = array_column($relateTasks, 'entity_id', 'entity_id');
                            $entityList = model(EntityModel::class)->where(['id' => ['IN', implode(',', $entityIdList)]])->select();
                            $entityList = array_column($entityList, null, 'id');
                            $entityList = array_map(function ($item) {
                                $entityJsonFields = json_decode($item['json'] ?? '{}', true);
                                return array_merge($item, $entityJsonFields);
                            }, $entityList);

                            foreach ($relateTasks as $relateTask) {
                                $k = $relateTask['initial_episode_code'] . '/' . $relateTask['showings_number'] . '/' . $relateTask['entity_name'] . $relateTask['entity_id'];
                                $groupKeyText[$k] = $relateTask['initial_episode_code'] . '/' . $relateTask['showings_number'] . '/' . $relateTask['entity_name'];
                                $relateTasksGrouped[$k][] = $relateTask;
                                $entity = $entityList[$relateTask['entity_id']] ?? null;
                                if (empty($entity)) {
                                    continue;
                                }
                                $currentModule = module_by_id($entity['module_id']);
                                if (!in_array(module_by_id($entity['module_id'])['code'], ['design', 'storyboard'])) {
                                    if ($currentModule['code'] === 'shot') {
                                        $moduleCode = 'storyboard';
                                        $entityId = $entity['shot_storyboard'];
                                    } else {
                                        $moduleCode = 'design';
                                        $entityId = $entity[$currentModule['code'] . '_design'];
                                    }
                                } else {
                                    $moduleCode = $currentModule['code'];
                                    $entityId = $entity['id'];
                                }
                                if (!isset($linkToData[$k])) {
                                    $linkToData[$k] = [
                                        'demand_id' => $noteId,
                                        'entity_id' => $entityId,
                                        'tenant_id' => $relateTask['tenant_id'],
                                        'project_id' => $relateTask['project_id'],
                                        'message_key' => 'entity_demand_change',
                                        'module_code' => $moduleCode
                                    ];
                                }
                            }
                            break;
                        case 'step':
                            $templateId = OptionsService::getInstance()->getTaskRemindCommonTemplateId();
                            $relateTasksGrouped = [];
                            foreach ($relateTasks as $relateTask) {
                                $k = $relateTask['initial_episode_code'] . '/' . $relateTask['showings_number'] . '/' . $relateTask['entity_name'] . '/' . $relateTask['step_name'];
                                $groupKeyText[$k] = $k;
                                $relateTasksGrouped[$k][] = $relateTask;
                                // module_code
                                if (!isset($linkToData[$k])) {
                                    $linkToData[$k] = [
                                        'demand_id' => $noteId,
                                        'entity_id' => $relateTask['entity_id'],
                                        'tenant_id' => $relateTask['tenant_id'],
                                        'project_id' => $relateTask['project_id'],
                                        'task_id' => $relateTask['id'],
                                        'message_key' => 'task_demand_change',
                                        'module_code' => in_array(module_by_id($relateTask['module_id'])['code'], ['design', 'asset', 'level']) ? 'asset' : 'shot',
                                    ];
                                }
                            }
                            break;
                        default:
                            continue 2;
                    }

                    foreach ($relateTasksGrouped as $key => $relateTasks) {
                        $relateText = $groupKeyText[$key];
                        $extraLinkToData = $linkToData[$key] ?? [];
                        $relateTextNotifyUserIdList = [];
                        $episodeNotifyParam = [
                            'first' => '需求变更通知',
                            'note_text' => $relateText . $notifyText,
                            'remark' => "请及时查看",
                            'demand_content' => mb_substr($note['text'], 0, 15),
                            'operate_at' => date("Y/m/d H:i:s", $data['operate_at']),
                            'operator' => $creator['name'] ?? 'unknown',
                            'demand_id' => $note['id'],
                            'module_code' => $note['module_code'],
                        ];
                        $episodeNotifyParam = array_merge($episodeNotifyParam, $extraLinkToData);
                        foreach ($relateTasks as $relateTask) {
                            // 去除重复的通知人
                            foreach ($relateTask['notify_union_id_list'] as $unionId) {
                                $relateTextNotifyUserIdList[$unionId] = $unionId;
                            }
                        }
                        foreach ($relateTextNotifyUserIdList as $unionId) {
                            if ($unionId <= 0) {
                                continue;
                            }
                            Client::send('send_notify_message_v2', build_queue_data_with_xu([
                                "param" => $episodeNotifyParam,
                                'receiver' => $unionId,
                                'template_id' => $templateId,
                                'content_type' => 'card_message',
                                'notice_type' => 'message_demand',
                                'is_popup' => 1,
                                'message_key' => $episodeNotifyParam['message_key'] ?? 'unknown',
                            ]));
                        }
                    }
                }
            }

        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
